﻿using System.Web;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Yakool.Order
{
    class InitTask : ITask
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private SpiderContext context;

        public InitTask(SpiderContext ctx)
        {
            context = ctx;
        }

        public void RunSynchronously()
        {
            context.RootDir = "./res";
            context.InputFile = Path.Combine(context.RootDir, "settings.js");
            context.IntermediateDir = Path.Combine(context.RootDir, DateTime.Now.ToString("yyyy-MM-dd_HH.mm.ss"));
            context.OutputFile = Path.Combine(context.IntermediateDir, "order.csv");

            if (!Directory.Exists(context.IntermediateDir))
            {
                Directory.CreateDirectory(context.IntermediateDir);
                log.InfoFormat("Create intermediate directory {0}", context.IntermediateDir);
            }

            LoadSettings();
            log.InfoFormat("settings.js loaded");

            Login();
            log.InfoFormat("Login successfully");
        }

        private void LoadSettings()
        {
            var raw = File.ReadAllText(context.InputFile);
            context.Settings = JArray.Parse(raw)[0];
        }

        private void Login()
        {
            var loginUrl = context.Settings["loginUrl"].ToString();
            var user = context.Settings["user"].ToString();
            var password = context.Settings["password"].ToString();
            var loginPayload = context.Settings["loginPayload"].ToString();

            loginPayload = string.Format(loginPayload, 
                HttpUtility.UrlEncode(user),
                HttpUtility.UrlEncode(password));

            var rs = HttpBot.Post(loginUrl, null, null, loginPayload);
            if(rs.Status != 302)
                throw new ApplicationException("Login failed");

            context.Cookie = rs.Cookie;
        }
    }
}
